﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVC3Demo.Models;
using KnowledgeEntity;

namespace MVC3Demo.Controllers
{
   public class AccountController : Controller
   {

      //
      // GET: /Account/LogOn

      public ActionResult LogOn()
      {
         return View();
      }

      //
      // POST: /Account/LogOn

      [HttpPost]
      public ActionResult LogOn(LogOnModel model, string returnUrl)
      {
         UserAccount user = UserAccountFactory.GetUserInstanceByCode(model.UserName);
         bool logon = UserAccountFactory.LogOn(model.UserName, model.Password);
         if (ModelState.IsValid)
         {
            if (user.NoSuchUser)
            {
               ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.InvalidUserName));

               return View(model);
            }

            if (!logon)
            {
               ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.InvalidPassword));

               return View(model);
            }

            FormsAuthentication.SetAuthCookie(user.Code, model.RememberMe);

            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
            {
               return Redirect(returnUrl);
            }
            else
            {
               return RedirectToAction("Index", "Home");
            }
         }

         return View(model);
      }

      //
      // GET: /Account/LogOff

      public ActionResult LogOff()
      {
         FormsAuthentication.SignOut();

         return RedirectToAction("Index", "Home");
      }

      //
      // GET: /Account/Register

      public ActionResult Register()
      {
         return View();
      }

      //
      // POST: /Account/Register

      [HttpPost]
      public ActionResult Register(RegisterModel model)
      {
         if (ModelState.IsValid)
         {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
               FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
               return RedirectToAction("Index", "Home");
            }
            else
            {
               ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
         }

         // If we got this far, something failed, redisplay form
         return View(model);
      }

      //
      // GET: /Account/ChangePassword

      [Authorize]
      public ActionResult ChangePassword()
      {
         return View();
      }

      //
      // POST: /Account/ChangePassword

      [Authorize]
      [HttpPost]
      public ActionResult ChangePassword(ChangePasswordModel model)
      {
         if (ModelState.IsValid)
         {

            // ChangePassword will throw an exception rather
            // than return false in certain failure scenarios.
            bool changePasswordSucceeded;
            try
            {
               MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
               changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
            }
            catch (Exception)
            {
               changePasswordSucceeded = false;
            }

            if (changePasswordSucceeded)
            {
               return RedirectToAction("ChangePasswordSuccess");
            }
            else
            {
               ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }
         }

         // If we got this far, something failed, redisplay form
         return View(model);
      }

      //
      // GET: /Account/ChangePasswordSuccess

      public ActionResult ChangePasswordSuccess()
      {
         return View();
      }

      #region Status Codes
      private static string ErrorCodeToString(MembershipCreateStatus createStatus)
      {
         // See http://go.microsoft.com/fwlink/?LinkID=177550 for
         // a full list of status codes.
         switch (createStatus)
         {
            case MembershipCreateStatus.DuplicateUserName:
               return "用户ID已存在，请输入一个新的ID。";

            case MembershipCreateStatus.DuplicateEmail:
               return "该e-mail已被使用，请输入一个新的e-mail地址。";

            case MembershipCreateStatus.InvalidPassword:
               return "登陆密码不正确，请重新输入。";

            case MembershipCreateStatus.InvalidEmail:
               return "e-mail地址不正确，请重新输入。";

            case MembershipCreateStatus.InvalidAnswer:
               return "e-mail取回答案输入不正确，请复查并重新输入。";

            case MembershipCreateStatus.InvalidQuestion:
               return "e-mail取回问题选择不正确，请复查并重试。";

            case MembershipCreateStatus.InvalidUserName:
               return "用名户不正确，请重新输入。";

            case MembershipCreateStatus.ProviderError:
               return "权限控制系统返回了一个错误，请核对您的输入并重试，如果错误仍然出现，请联系系统管理员。";

            case MembershipCreateStatus.UserRejected:
               return "用户创新请求已被取消，请核对您的输入并重试，如果错误仍然出现，请联系系统管理员。";

            default:
               return "发生未知错误，请核对您的输入并重试，如果错误仍然出现，请联系系统管理员。";
         }
      }
      #endregion
   }
}
